import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store/index.js'

// import Login from '../views/login/login.vue'
const Login = () => import('../views/login/login.vue')
// import Main from '../views/main/main.vue'
const Main = () => import('../views/main/main.vue')

// import Home from '@/views/Home/Home.vue'
const Home = () => import('@/views/Home/Home.vue')

// import User from '@/views/User/User.vue'
const User = () => import('@/views/User/User.vue')

// import Search from '@/views/Search/Search.vue'
const Search = () => import('@/views/Search/Search.vue')

// import SearchResult from '../views/Search/SearchResult.vue'
const SearchResult = () => import('../views/Search/SearchResult.vue')

// import ArticleDetail from '../views/ArticleDetail/ArticleDetail.vue'

const ArticleDetail = () => import('../views/ArticleDetail/ArticleDetail.vue')

// import UserEdit from '../views/UserEdit/UserEdit.vue'
const UserEdit = () => import('../views/UserEdit/UserEdit.vue')

// import Chat from '../views/Chat/Chat.vue'
const Chat = () => import('../views/Chat/Chat.vue')
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login,
    name: 'login'
  },
  {
    path: '/',
    component: Main,
    children: [
      // path 为"空字符串"的子路由规则，叫做"默认子路由"
      { path: '', component: Home, name: 'home', meta: { isRecord: true, top: 0 } },
      { path: '/user', component: User, name: 'user' }
    ]
  },
  { path: '/search', component: Search, name: 'search' },
  // 搜索结果页
  { path: '/search/:kw', component: SearchResult, name: 'search-result', props: true, meta: { isRecord: true, top: 0 } },
  { path: '/article/:id', component: ArticleDetail, name: 'art-detail', props: true, meta: { isRecord: true, top: 0 } },
  { path: '/user/edit', component: UserEdit, name: 'user-edit' },
  { path: '/chat', component: Chat, name: 'chat' }
]

const router = new VueRouter({
  routes
})
// 所有有权限页面的路径，都在这个数组之中
const pagePathArr = ['/user', '/user/edit']

// 为路由的实例对象挂载全局前置守卫
router.beforeEach((to, from, next) => {
  // 访问的是有权限的页面，需要判断用户是否登录
  if (pagePathArr.indexOf(to.path) !== -1) {
    // 1. 从 store 中获取 token 的值
    //    注意：store.state.tokenInfo 要么是 {} 空对象，要么是包含 {token, refresh_token} 的对象
    const tokenStr = store.state.tokenInfo.token
    if (tokenStr) {
      // 1.1 token 有值，已登录过（操作：直接放行）
      next()
    } else {
      // 1.2 token 不存在，没有登录（操作：强制跳转到登录页）
      next(`/login?pre=${to.fullPath}`)
    }
  } else {
    // 访问的是没有权限的页面
    next()
  }
})

router.afterEach((to, from) => {
  if (to.meta.isRecord) {
    console.log(to.meta.top)
    Vue.nextTick(function () {
      window.scrollTo(0, to.meta.top)
    })
  }
})

export default router
